<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getProducts">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="onSale">上架</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="offSale">下架</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表
		v-loading="listLoading" 是否显示加载圈
		@selection-change=  选择发生改变都会触发事件
		-->
		<el-table :data="products" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<!--用来做多选的，以便批量删除-->
			<el-table-column type="selection" width="55">
			</el-table-column>
			<!--索引值-->
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="名称" width="120" sortable>
			</el-table-column>
			<el-table-column prop="saleprice" label="售价" width="100"  sortable>
			</el-table-column>
			<el-table-column prop="costprice" label="成本价" width="100"  sortable>
			</el-table-column>
			<el-table-column prop="salecount" label="销量" width="100" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="120"  sortable>
                <template scope="scope">
                    <span v-if="scope.row.state==0" style="color: red">下架</span>
                    <span v-else style="color: blue">上架</span>
                </template>
			</el-table-column>
			<el-table-column prop="offsaletime" label="下架时间" width="100" sortable>
			</el-table-column>
			<el-table-column prop="onsaletime" label="上架时间" min-width="120" sortable>
			</el-table-column>
			<el-table-column label="操作" width="250">
				<template scope="scope">
					<el-button size="small" type="info" @click="handleEdit(scope.$index, scope.row)">详情</el-button>
					<el-button size="small" type="warning" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面 v-model="productFormVisible" -->
		<el-dialog title="新增或编辑" :visible.sync="productFormVisible" :close-on-click-modal="false">
			<!--:rules 校验-->
			<el-form :model="productForm" label-width="80px" :rules="productFormRules" ref="productForm">
				<el-form-item label="名称" prop="name">
					<el-input v-model="productForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="售价" prop="saleprice">
					<el-input v-model="productForm.saleprice" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="成本价" prop="costprice">
					<el-input v-model="productForm.costprice" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="资源" prop="resources">
					<!--<el-input v-model="productForm.resources" auto-complete="off"></el-input>-->
					<!--:on-preview="handlePreview" 预览-->
					<!--:on-remove="handleRemove" 删除-->
					<!--:on-success="handleSuccess" 上传成功-->
					<!--:file-list="fileList" 做回显-->
					<!--action="http://localhost:8080/dfs" 上传路径,封装的接口地址，它是没有通过axios发请求-->
					<el-upload
							class="upload-demo"
							action="http://localhost:8080/dfs"
							:on-preview="handlePreview"
							:on-remove="handleRemove"
							:on-success="handleSuccess"
							:file-list="fileList"
							list-type="picture">
						<el-button size="small" type="primary">点击上传</el-button>
						<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
					</el-upload>

				</el-form-item>
				<el-form-item label="简介" prop="intro">
					<!--<el-input v-model="productForm.detail.intro" auto-complete="off"></el-input>-->
					<quill-editor v-model="productForm.detail.intro"
								  :options="quillOption"
					>

					</quill-editor>
				</el-form-item>
				<el-form-item label="预约须知" prop="orderNotice">
					<!--<el-input v-model="productForm.detail.orderNotice" auto-complete="off"></el-input>-->
					<quill-editor v-model="productForm.detail.orderNotice"  :options="quillOption">

					</quill-editor>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="productFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="save" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
    import { quillEditor } from "vue-quill-editor"; //调用编辑器
    import 'quill/dist/quill.core.css';
    import 'quill/dist/quill.snow.css';
    import 'quill/dist/quill.bubble.css';
    import quillConfig from '../../common/js/quill-config';
	export default {
        components: {
            quillEditor
        },
		data() {
			return {
			    quillOption:quillConfig,
                page: 1,
				query: {
					keyword: ''
				},
                fileList:[],
				products: [],
				total: 0,

				listLoading: false,
				sels: [],//列表选中列

				//添加获取编辑
				productFormVisible: false,//编辑界面是否显示
				editLoading: false,
				productFormRules: {
					name: [
						{ required: true, message: '请输入名称', trigger: 'blur' },
					]
				},
				//编辑界面数据
				productForm: {
					id: null,
					name: '',
                    saleprice: 0,
                    costprice: 0,
                    resources: '',
                    detail:{
					    intro:'',
                        orderNotice:''
					}
				}
			}
		},
		methods: {
            onSale(){
                if(this.sels==null || this.sels.length<1){
                    this.$message({ message: '老铁，你不选中数据，臣妾上架不了啊....',type: 'error'});
                    return;
				}
                var ids = this.sels.map(item => item.id);
                this.$confirm('确认上架选中记录吗？', '温馨提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    this.$http.patch("/product/onSale",ids)
                        .then(result=>{
                            this.listLoading = false;
                            result = result.data;
                            if(result.success){
                                this.$message({
                                    message: '上架成功',
                                    type: 'success'
                                });
							}else{
                                this.$message({
                                    message: result.message,
                                    type: 'error'
                                });
							}

                            this.getProducts();
                        })
                        .catch(result=>{
                            this.$message({
                                message: result.data.message,
                                type: "error"
                            });
                        })
                }).catch(() => {
                    //取消后操作
                    this.$message({
                        type: 'info',
                        message: '已取消上架'
                    });
                });
			},
			offSale(){
                if(this.sels==null || this.sels.length<1){
                    this.$message({ message: '老铁，你不选中数据，臣妾下架不了啊....',type: 'error'});
                    return;
                }
                var ids = this.sels.map(item => item.id);
                this.$confirm('确认下架选中记录吗？', '温馨提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    this.$http.patch("/product/offSale",ids)
                        .then(result=>{
                            this.listLoading = false;
                            result = result.data;
                            if(result.success){
                                this.$message({
                                    message: '下架成功',
                                    type: 'success'
                                });
                            }else{
                                this.$message({
                                    message: result.message,
                                    type: 'error'
                                });
                            }
                            this.getProducts();
                        })
                        .catch(result=>{
                            this.$message({
                                message: result.data.message,
                                type: "error"
                            });
                        })
                }).catch(() => {
                    //取消后操作
                    this.$message({
                        type: 'info',
                        message: '已取消下架'
                    });
                });
			},
            handleSuccess(response, file, fileList){
                //1,2,3
                console.log(fileList); //response.resultObj
				let resourcesTmp = '';
                for(let i=0;i<fileList.length;i++){
                    if(i==fileList.length-1){
                        //最后一个不要加逗号
                        resourcesTmp=resourcesTmp+fileList[i].response.resultObj;
					}else{
                        resourcesTmp=resourcesTmp+fileList[i].response.resultObj+",";
					}
				}
                this.productForm.resources = resourcesTmp;
            },
            handleRemove(file, fileList) {
                console.log(file);

                var filePath =file.response.resultObj;
                //通过axios发请求，不需要localhost:8080
                this.$http.delete("/dfs/?path="+filePath)
                    .then(res=>{
                        if(res.data.success){
                            this.$message({
                                message: '删除成功!',
                                type: 'success'
                            });
                            //1,2,3
                            console.log(fileList); //response.resultObj
                            let resourcesTmp = '';
                            for(let i=0;i<fileList.length;i++){
                                if(i==fileList.length-1){
                                    //最后一个不要加逗号
                                    resourcesTmp=resourcesTmp+fileList[i].response.resultObj;
                                }else{
                                    resourcesTmp=resourcesTmp+fileList[i].response.resultObj+",";
                                }
                            }
                            this.productForm.resources = resourcesTmp;
                        }else{
                            this.$message({
                                message: '删除失败!',
                                type: 'error'
                            });
                        }
                    })
            },

            handlePreview(file) {
                console.log(file);
            },
            getProductDetail(productId){
				this.$http.get("/product/detail/"+productId)
					.then(result=>{
					    if(result.data){

                            this.productForm.detail = result.data;
                        }
					})
			},
			handleCurrentChange(val) {
				this.page = val;
				this.getProducts();
			},
			//获取部门列表
            getProducts() {
				let para = {
                    currentPage: this.page,
					keyword: this.query.keyword
				};
				this.listLoading = true;

				this.$http.post("/product",para)
					.then(result=>{
					    console.log(result)
					    this.products = result.data.data;
					    this.total = result.data.total;
                        this.listLoading = false;
					})
					.catch(result=>{
					    alert(result);
					})
			},
			//删除
			handleDel: function (index, row) {
			    console.log(row);
				this.$confirm('确认删除该记录吗?', '温馨提示', {
					type: 'warning'
				}).then(() => {
				    //确认后操作
					this.listLoading = true;

					///product/1
					let url = "/product/"+row.id
					this.$http.delete(url)
                        .then(result=>{
                            //关闭加载框
                            this.listLoading = false;
                            //提示删除成功 ajax success message
                            console.log(result);
                            result = result.data
                            if(result.success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                            }else{
                                this.$message({
                                    message: result.message,
                                    type: 'error'
                                });
                            }
                            //从新加载数据
                            this.getProducts();
                        })

				}).catch(() => {
				    //取消后操作
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });

                });
			},
			//显示编辑界面
			handleEdit: function (index, row) {
			    //打开对话框
				this.productFormVisible = true;
				//回显 拷贝当前行数据给模型，这个模型绑定到form，由于双向绑定自动做回显
				this.productForm = Object.assign({}, row);
                this.productForm.detail = {"intro":'',"orderNotice":''}
                this.getProductDetail(row.id);

				//做图片回显  fileList
				this.fileList = []; //清空原来数据
                let resources = this.productForm.resources; //1.jpg,2.jpg
				if(resources){
                    resources = resources.split(",");
				    for(let i=0;i<resources.length;i++){
				        let url = "http://122.51.119.246:8888"+resources[i];
				        this.fileList.push({"url":url,"response":{
				            "resultObj":resources[i],
							}})
					}
				}
			},
			//显示新增界面
			handleAdd: function () {
			    //打开对话框
				this.productFormVisible = true;

				//清空数据
				this.productForm = {
                    id: null,
                    name: '',
                    saleprice: 0,
                    costprice: 0,
                    resources: '',
                    detail:{
                        intro:'',
                        orderNotice:''
                    }
                }

			},
			//编辑
            save: function () {
			    // 在form上面加了这个内容ref="productForm"
				this.$refs.productForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认保存吗？', '温馨提示', {}).then(() => {
							this.editLoading = true;

							//如果有必要在封装数据
							let para = Object.assign({}, this.productForm);

							//级联狂获取是一个数组，需要自己封装数据
							if(this.productForm.parent){
                                console.log(this.productForm.parent)
                                let ids =  this.productForm.parent;
                                para.parent = {
                                    id:ids[ids.length-1]
                                }
							}

							this.$http.put("/product",para)
								.then((res) => {
									this.editLoading = false;
									res = res.data;
									if(res.success){
                                        this.$message({
                                            message: '保存成功',
                                            type: 'success'
                                        });
									}else{
                                        this.$message({
                                            message: res.message,
                                            type: 'error'
                                        });
                                    }
									this.$refs['productForm'].resetFields();

									//关闭对话框
									this.productFormVisible = false;
									//重新加载数据
									this.getProducts();
							});
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
			    //[{id:1,name:zs},{.....}]
				var ids = this.sels.map(item => item.id);
				console.log(ids);
				this.$confirm('确认删除选中记录吗？', '温馨提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
                    console.log(ids);
                    //axios get delete 不支持传对象
					this.$http.patch("/product/bulk",ids)
						.then(result=>{
                            this.listLoading = false;
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.getProducts();
						})
						.catch(result=>{
                            this.$message({
                                message: result.data.message,
                                type: "error"
                            });
						})
				}).catch(() => {
                    //取消后操作
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
				});
			}
		},
		mounted() {
			this.getProducts();
		}
	}

</script>

<style scoped>

</style>